/**
 * 触发 window.resize
 */
import store from '@/store'
import { projectDetail } from '@/api/project'

export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    (event) => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE () {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

export function scorePassword (pass) {
  let score = 0
  if (!pass) {
    return score
  }
  // award every unique letter until 5 repetitions
  const letters = {}
  for (let i = 0; i < pass.length; i++) {
    letters[pass[i]] = (letters[pass[i]] || 0) + 1
    score += 5.0 / letters[pass[i]]
  }

  // bonus points for mixing it up
  const variations = {
    digits: /\d/.test(pass),
    lower: /[a-z]/.test(pass),
    upper: /[A-Z]/.test(pass),
    nonWords: /\W/.test(pass)
  }

  let variationCount = 0
  for (var check in variations) {
    variationCount += variations[check] === true ? 1 : 0
  }
  score += (variationCount - 1) * 10

  return parseInt(score)
}

export function download (url, name) {
  const xhr = new XMLHttpRequest()
  xhr.open('get', url, true)
  xhr.setRequestHeader('token', store.getters.token)
  xhr.responseType = 'blob'
  xhr.onload = (e) => {
    const a = document.createElement('a')
    const { response } = e.currentTarget
    const url = URL.createObjectURL(response)
    a.href = url
    a.download = name
    a.click()
    window.URL.revokeObjectURL(url)
  }
  xhr.send()
}

export default {
  install (Vue) {
    // 防止重复回车
    Vue.directive('preventReClick', {
      inserted (el, binding) {
        el.addEventListener('keydown', (event) => {
          if (event.keyCode === 13 && !el.disabled) {
            el.disabled = true
            setTimeout(() => {
              el.disabled = false
            }, binding.value || 1000)
          }
        })
      }
    })
  }
}

export function parameterChange (data) {
  let res = ``
  for (const key in data) {
    if (data[key] || data[key] === 0) res = `${res}&${key}=${data[key]}`
  }
  return res.substr(1)
}

export const projectDetails = (project_id) => {
  return new Promise((resolve, reject) => {
    projectDetail({ project_id }).then((res) => {
      if (res.code === 200) {
        const { project_name, default_language_id: language_id, project_language } = res.data
        const language = []
        const checkedArr = []
        let defaultLanguage = {}

        project_language.forEach((item) => {
          if (item.language_id === language_id) defaultLanguage = item
          else {
            language.push(item.language_id)
            checkedArr.push(item.language)
          }
        })
        language.unshift(language_id)
        checkedArr.unshift(defaultLanguage.language)

        const form = { project_id, project_name, language_id, language }
        resolve({ checkedArr, defaultLanguage, form })
      }
    })
  })
}

const typeMap = { project: 0, app: 1, module: 2, string: 3 }
let treeDataCache = []
let flag = true
// 递归树组件数据
export const generator = (treeData, parentNode) => {
  if (flag || store.getters.isNewApp) {
    treeDataCache = treeData
    flag = false
    store.commit('SET_IS_NEW_APP', false)
    // console.log('treeDataCache:', treeDataCache)
  }
  // eslint-disable-next-line camelcase
  return treeData.map((item) => {
    const isProjectNode = Object.keys(item).includes('project_name')
    const isAppNode = Object.keys(item).includes('app_name')
    const isModuleNode = Object.keys(item).includes('module_name')
    const isStringNode = Object.keys(item).includes('string_name')

    let label = ''
    let value = ''
    let order = -1
    let key = ''
    let type = -1
    let parentId = ''
    let projectId = ''
    let appId = ''
    let moduleId = ''
    let children = []

    key = isProjectNode ? 'project' : isAppNode ? 'app' : isModuleNode ? 'module' : isStringNode ? 'string' : ''
    type = typeMap[key]

    const {
      project_name,
      project_id,
      project_order,
      app,
      app_name,
      app_id,
      app_order,
      module,
      module_name,
      module_id,
      module_order,
      string_list,
      string_name,
      string_id,
      string_order
    } = item
    switch (key) {
      case 'project':
        label = project_name
        value = project_id
        order = project_order
        key = `${key}_${value}`
        projectId = project_id
        children = [...app]
        break
      case 'app':
        label = app_name
        value = app_id
        order = app_order
        key = `${key}_${value}`
        projectId = project_id
        appId = app_id
        parentId = project_id
        children = [...module]
        break
      case 'module':
        label = module_name
        value = module_id
        order = module_order
        key = `${key}_${value}`
        projectId = parentNode.project_id
        appId = app_id
        moduleId = module_id
        parentId = app_id
        children = [...string_list]
        break
      case 'string':
        label = string_name
        value = string_id
        order = string_order
        key = `${key}_${value}`
        appId = parentNode.app_id
        moduleId = module_id
        parentId = module_id

        let tempApp = {}
        treeDataCache.forEach((project) => {
          const temp = project.app.find((app) => {
            return app.app_id === appId
          })
          if (temp) tempApp = temp
        })
        projectId = tempApp.project_id
        break
      default:
        break
    }

    const current = { label, value, order, key, type }

    if (parentId) current.parentId = parentId
    if (projectId) current.projectId = projectId
    if (appId) current.appId = appId
    if (moduleId) current.moduleId = moduleId
    if (children && children.length) current.children = generator(children, item)
    return current
  })
}

// 递归树组件数据（翻译管理版）
export const generator_translate = (treeData) => {
  return treeData.map((item) => {
    const { project_name, project_id, project_order } = item

    const current = {
      label: project_name,
      value: project_id,
      order: project_order,
      key: `project_${project_id}`,
      type: 0,
      children: []
    }

    return current
  })
}

/**
 * 获取字符串长度，英文字符 长度1，中文字符长度2
 * @param {*} str
 */
export const getStrFullLength = (str = '') =>
  str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      return pre + 1
    }
    return pre + 2
  }, 0)

/**
 * 截取字符串，根据 maxLength 截取后返回
 * @param {*} str
 * @param {*} maxLength
 */
export const cutStrByFullLength = (str = '', maxLength) => {
  let showLength = 0
  return str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      showLength += 1
    } else {
      showLength += 2
    }
    if (showLength <= maxLength) {
      return pre + cur
    }
    return pre
  }, '')
}
